﻿//Copyright (C) <2013>  <jonathan cleeve norton> All Rights Reserved 
//Contact jon.norton@fin-plus.co.uk website <http://www.fin-plus.co.uk/>
using System;
using FinPlusAssembler;
using FinPlusInterfaces;

namespace FinPlusCompCore
{
    //private classes
    internal class Accumulator
    {
        public IPod Model { get; private set; }
        public IPod Values { get; private set; }
        public string TotalKey { get; private set; }
        public double Total { get; private set; }

        private static int _id;

        public Accumulator(string name, string[] keyLabels, string key, char keyDelimitor, string user, bool isVisible = true)
        {
            _id++;
            var keys = key.Split(keyDelimitor);
            TotalKey = key.Substring(0, key.LastIndexOf("|") + 1) + "Total";
            Values = IOC.New<IPod>(name, _id.ToString(), user, _id);
            Model = IOC.New<IPod>(name, _id.ToString(), user, _id);
            Model.TryAdd(Values.Add(name, 0.0));

            if (isVisible)
                for (int x = 0; x < keyLabels.Length; x++)
                    Model.TryAdd(Values.Add(keyLabels[x], keys[x]));
        }

        public double Update(string key, double value, int rounding, bool IsChange, bool isTotal, bool isVisible = true)
        {
            value = Math.Round(value, rounding);
            var bean = Values.Get(key);
            var pValue = 0.0;

            if (bean != null)
            {
                pValue = (double)Values.Value(key);
                bean.Update(value += IsChange ? pValue : 0, null, false);
            }
            else
            {
                bean = Values.Add(key, 0.0);
                if (isVisible)
                    Model.TryAdd(bean);
                bean.Update(value, null, false);
            }

            if (!isTotal)
                Total += value;

            return value -= pValue;
        }
    }
}
